module Main where 

import Text.Printf
import Control.Monad
import Control.Concurrent
import Control.Exception
import System.IO
import Text.Printf

import Network
import qualified Network.Socket as NetS

import Net

print_connect :: NetS.Socket -> NetS.SockAddr -> IO ()
print_connect sock sockaddr = do
  printf "\nConnected by:"
  print sock
  print sockaddr
  receiveData sock
  NetS.close sock
  NetS.close sock
  NetS.close sock
  

serveLoop listeningSocket = do
  ( acceptedSocket, acceptedSocketAddr ) <- NetS.accept listeningSocket
  forkIO (print_connect acceptedSocket acceptedSocketAddr)
  serveLoop listeningSocket


serve  host port maxConnections = NetS.withSocketsDo $ do
  sock <- tcpSocket
  NetS.bindSocket sock ( NetS.SockAddrInet port host )
  NetS.listen sock maxConnections
  serveLoop sock

main = serve localhost (fromIntegral port) 16